package com.tanhua.sso.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;
    /**
     * 用户登录
     * @param phone
     * @param code
     * @return
     */
    public String login(String phone, String code) {
        String redisKey = "CHECK_CODE_" +phone;
        boolean isNew  =false;

        //效验验证码
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.equals(code,redisData)){
            return  null;//验证码错误
        }
        //验证码在验证完成后,需要废弃
        this.redisTemplate.delete(redisKey);
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("mobile", phone);
        User user = this.userMapper.selectOne(userQueryWrapper);


        if (null == user){
            //需要注册该用户
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
          //注册用户
            this.userMapper.insert(user);
            isNew = true;
        }

        //生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",user.getId());

        String token = Jwts.builder()
                .setClaims(claims) //plsyload 存放数据的位置,不能防止敏感数据,如:密码
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(1).toDate()) //设置过期时间1小时
                .compact();


        return token + "|" + isNew;
    }

    public User queryUserByToken(String token) {
     try {
         //通过token解析数据
         Map<String, Object> body = Jwts.parser()
                 .setSigningKey(secret)
                 .parseClaimsJws(token)
                 .getBody();

         User user = new User();
         user.setId(Long.valueOf(body.get("id").toString()));
        //需要返回user对象中的mobile,需要查询数据库获取mobile
        //如果每次都查询数据库,必然会导致性能问题,需要对用户的手机号进行缓存操作
        //数据缓存时需要设置过期时间,过期时间要与token的事件一致
         //如果用户修改了手机号,需要同步修改redis中的数据
         String redisKey  = "TANHUA_USER_MOBILE_" +user.getId();
         if (this.redisTemplate.hasKey(redisKey)){
             String mobile = this.redisTemplate.opsForValue().get(redisKey);
             user.setMobile(mobile);
         }else {
             //查询数据库
             User u = this.userMapper.selectById(user.getId());
             user.setMobile(u.getMobile());
             //将手机号写入到redis中
             //在jwt中的过期时间单位为:秒
             long timeout = Long.valueOf(body.get("exp").toString())*1000 - System.currentTimeMillis();
             this.redisTemplate.opsForValue().set(redisKey,u.getMobile(),timeout, TimeUnit.MILLISECONDS);
         }
        return  user;

     }catch (ExpiredJwtException e){
         log.info("token已经过期~ token =" + token);

     }catch (Exception e){
         log.error("token不合法 ~ token =" + token ,e);

     }
        return  null;
    }
}
